package com.blockmeta.bbs.baselibrary.utils;

import android.content.Context;
import android.graphics.Paint;
import android.view.WindowManager;

import com.blockmeta.bbs.baselibrary.base.app.BaseApp;

/**
 * @author AirThor
 * @date 2019/6/14.
 */
public class DimentionsUtil {
    public static int dp2px(float dpValue) {
        return dp2px(BaseApp.getApp(),dpValue);
    }

    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 將sp轉換為px
     *
     * @param spValue
     * @return
     */
    public static int sp2px(float spValue) {
        final float fontScale = BaseApp.getApp().getResources().getDisplayMetrics().density;
        return (int) (spValue * fontScale + 0.5f);
    }
    /**
     * 获取手机状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        if (context==null) {return 0;}
        int height = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            height = context.getResources().getDimensionPixelSize(resourceId);
        }
        return height;
    }

    /**
     * 获取屏幕宽
     * */
    public static int getWindowWith(Context context){
        WindowManager systemService = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return systemService==null?0:systemService.getDefaultDisplay().getWidth();
    }

    public static float getScreenWidthPixel() {
        return BaseApp.getApp().getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 获取屏幕高
     * */
    public static int getWindowHeight(Context context){
        WindowManager systemService = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return systemService==null?0:systemService.getDefaultDisplay().getHeight();
    }

    /**
     * 計算字體大小
     *
     * @param str      顯示文字
     * @param maxWidth 長度範圍
     * @return
     */
    public static float determineMaxTextSize(String str, float maxWidth) {
        int size = 0;
        Paint paint = new Paint();

        do {
            paint.setTextSize(++size);
        }
        while (paint.measureText(str) < maxWidth);

        // 精確到小數第一位
        float tSize = size * 1.f;
        do {
            paint.setTextSize(tSize += 0.1f);
        }
        while (paint.measureText(str) < maxWidth);
        return tSize;
    }
}
